package com.zj.processors.platform;

import com.zj.bean.TableInfo;
import com.zj.job.CommonJob;
import com.zj.processors.BaseCommonProcessor;
import com.zj.util.DateUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.velocity.VelocityContext;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.Date;

@Component
public class ApiProcessor extends BaseCommonProcessor {


    @Override
    public String getName() {
        return "api";
    }

    @Override
    public String process(TableInfo tableInfo, CommonJob commonJob) {
        init(tableInfo, commonJob);
        try {
            createFiles();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "ok";
    }

    private String getPackageName(String tableName) {

        if(tableName.contains("_")){
            tableName = tableName.substring(tableName.indexOf("_"), tableName.length());
        }
        tableName=tableName.replaceAll("_", "");
        return tableName.toLowerCase();
    }

    private void makedir(String dirPath) {
        File file = new File(dirPath);
        if (!file.exists()) {
            file.mkdir();
        }
    }
    public String createFiles() throws Exception {

        String moduleName= "";
        if(StringUtils.isNotEmpty(getParam("moduleName"))){
            moduleName=getParam("moduleName").trim();
        }
        String filePath = getParam("baseDir") + "java/com/zj/" +moduleName ;
        makedir(filePath);
        VelocityContext context = new VelocityContext();
        String modelName=convertDomainName(tableInfo.getTableName());
        context.put("modulePackage", moduleName);
        context.put("modelDesc", tableInfo.getDescription());
        context.put("modelName", modelName);
        context.put("modelProperty", lowFirstChar(modelName));
        context.put("servicePackage", getParam("servicePackage"));
        context.put("modelDesc", getParam("modelDesc"));
        context.put("dateStr", DateUtil.getyyyy_MM_dd_hms(new Date()));
        String serviceName=getParam("serviceName");
        if(StringUtils.isEmpty(serviceName)){
            serviceName=convertServiceName(this.tableInfo.getTableName());
        }
        log("use serviceName: " + serviceName);

        context.put("serviceName",serviceName);
        context.put("serviceProperty", lowFirstChar(serviceName));
        String businessPackage=getParam("businessPackage");
        String businessFolder="";
        if(!StringUtils.isEmpty(businessPackage)){
            context.put("businessPackage", "."+businessPackage);
            businessFolder=businessPackage+"/";
        }

        writeFile(context,"platform-vm/apiTemplate.vm",filePath +"/api/"+businessFolder+modelName+"Api.java");

        commonJob.log("task ok");
        return "ok";
    }

}
